package org.example.ctsbocc.controller;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.ctsbocc.utils.CreateVerificationCodeImage;
import org.example.ctsbocc.utils.LoggerUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;

@Controller
@RequestMapping("/api/verificationCode")
public class OutVerificationCodeController {
    @GetMapping("/generate")
//    @CrossOrigin(origins = "*", allowCredentials = "false")
    public ResponseEntity<byte[]> generateLoginVerifyCode(HttpSession session) {
        try {
            // 获取验证码信息
            BufferedImage verifyCodeImage = CreateVerificationCodeImage.getVerifiCodeImage();
            String verifyCode = String.valueOf(CreateVerificationCodeImage.getVerifiCode());

            // 存储验证码Session
            session.setAttribute("rightCode", verifyCode);
            LoggerUtil.log().info("于 {} 生成验证码：{}", LocalDateTime.now(), verifyCode);
//            LoggerUtil.log().info("当前 Session ID: {}", session.getId());

            // 转换为字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(verifyCodeImage, "JPEG", baos);
            byte[] imageBytes = baos.toByteArray();

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            headers.setCacheControl("no-cache, no-store, must-revalidate");
            headers.setPragma("no-cache");
            headers.setExpires(0);
//            headers.add("Access-Control-Allow-Origin", "*");

            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            LoggerUtil.log().error("验证码生成失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

}
